package com.cwx.mychat.login;

import com.alibaba.fastjson.JSON;
import com.cwx.mychat.utils.R;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationTargetUrlRequestHandler;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * 作者： cwx
 * 时间： 2024/10/19 0:33
 * 版本： 1.0
 * 注释：
 */
@Slf4j
@Component
public class LoginFailureHandler extends AbstractAuthenticationTargetUrlRequestHandler implements AuthenticationFailureHandler {


    @Override
    public void onAuthenticationFailure(HttpServletRequest request,
                                        HttpServletResponse response,
                                        AuthenticationException exception) throws IOException, ServletException {

        log.error("登录失败,返回错误信息, {}", exception.getMessage());
        String errorMassage = exception.getMessage();
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        response.setCharacterEncoding("UTF-8");
        PrintWriter writer = response.getWriter();
        String string = JSON.toJSONString(R.error( errorMassage));
        writer.print(string);
        writer.flush();
        writer.close();
    }
}
